/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socof_webcrawler;

import DataBase.Coleccao;

public class ControllerDownload extends Thread {

    private static ControllerDownload dc = new ControllerDownload();
    private static final int WAIT_TIME = 1000;
    private static final int THRESHOLD = 10000;
    private Coleccao cl = new Coleccao();

    private ControllerDownload() {
    }

    public static ControllerDownload getInstance() {
        return dc;
    }

    @Override
    public void run() {
        Bandwith bwa = Bandwith.getInstance();
        LaunchDownloaders dl = LaunchDownloaders.getInstance();

        try {
            while (!isInterrupted()) {
                if (cl.listaVazia() == true) {
                    dl.removeAllDownloaders();
                } else {
                    long sizeDownloading = bwa.getSizeDownloading();
                    long maxDownloading = dl.getMaxBandwidthAllocation();
                    if (sizeDownloading > maxDownloading) {
                        dl.decreaseDownloaders();
                    } else if ((sizeDownloading + THRESHOLD) < maxDownloading) {
                        dl.increaseDownloaders();
                    }
                }
                Thread.sleep(WAIT_TIME);
            }
        } catch (InterruptedException ex) {
        }
    }
}
